<template>
    <div class="common-table" ref="tableRef">
        <header v-if="showTableOpt" class="mb-2 flex w-full justify-between items-center">
            <div class="left">
                <a-button class="ml-1" @click="handleAdd" :icon="h(PlusOutlined)">
                    新增
                </a-button>
            </div>
            <div class="right">
                <a-tooltip placement="top">
                    <template #title>
                        <span>刷新</span>
                    </template>
                    <a-button class="ml-1" @click="handleAdd" :icon="h(RetweetOutlined)"></a-button>
                </a-tooltip>

                <a-dropdown>
                    <template #overlay>
                        <a-menu>
                            <a-menu-item key="1" @click="onExportTable">
                                导出本页数据
                            </a-menu-item>
                            <a-menu-item key="2" @click="onExportTableAll">
                                导出全部数据
                            </a-menu-item>
                        </a-menu>
                    </template>
                    <a-button class="ml-1" :icon="h(CloudDownloadOutlined)"></a-button>
                </a-dropdown>

                <a-tooltip placement="top">
                    <template #title>
                        <span>打印</span>
                    </template>
                    <a-button class="ml-1" @click="onPrintTable" :icon="h(PrinterOutlined)"></a-button>
                </a-tooltip>
                <a-popover
                    placement="top"
                    trigger="click"
                    :arrow-point-at-center="true"
                >
                    <template #content>
                        <div class="setting-popover">
                            <a-checkbox
                            v-model:checked="state.checkAll"
                            :indeterminate="state.indeterminate"
                            @change="onCheckAllChange"
                            >
                                全选
                            </a-checkbox>
                            <div class="divider"></div>
                            <a-checkbox-group v-model:value="state.checkedList" @change="handleCheckChange" >
                                <a-checkbox 
                                    v-for="item in props.colsCheckList"
                                    :key="item.dataIndex"
                                    :value="item.key">
                                    {{ item.title }}
                                </a-checkbox>
                            </a-checkbox-group>
                        </div>
                    </template>
                    <a-button class="ml-1" :icon="h(SettingOutlined)"></a-button>
                </a-popover>
            </div>
        </header>
        <a-table 
            :columns="columns" 
            :data-source="data" 
            :bordered="bordered"
            :scroll="{ y: 500,x: 1300 }"
            :pagination="pagination"
            :loading="loading"
            @change="handleChange"
            
        >
            <template #bodyCell="slotProps">
                <slot name="bodyCell" v-bind="slotProps"/>
            </template>
        </a-table>
    </div>
</template>

<script setup lang="ts">
import { exportExcel, showMsg } from '@/utils';
import { CloudDownloadOutlined, PlusOutlined, PrinterOutlined, RetweetOutlined, SettingOutlined } from '@ant-design/icons-vue';
import { onMounted, ref, nextTick, h,reactive, watch } from 'vue'
import type { EmptyObjectType } from './types';
import { useThemeConfig } from '@/stores/themeConfig';
import { storeToRefs } from 'pinia';

const emits = defineEmits<{
    (e:"change",pagination:{current:number,pageSize:number}):void,
    (e:'add'):void,
    (e:"print") :void,
    (e:"colsChecked",arr:string[]):void, //列展示
}>()

const props = withDefaults(defineProps<{
    columns: any[],
    data: any[],
    bordered?: boolean,
    pagination?:boolean | object,
    loading:boolean,
    showTableOpt?:boolean,
    colsCheckList?:any //操作列提前过滤保留一列，否则atable的columns列遍历的时候插槽报错undefined
    exportFileName?:string
}>(),{
    bordered:true,
    loading:false,
    pagination:false,
    showTableOpt:false,
    colsCheckList:[]
})

const themeConfigStore = useThemeConfig()
const {themeConfig}= storeToRefs(themeConfigStore)
const tableRef = ref<HTMLElement>()
const tableHeight = ref(550)

const state = reactive({
    checkedList:props.colsCheckList.map((i:any)=>i.key) as string[], // 选中的列表
    checkAll:true,
    indeterminate:false,
})
const onCheckAllChange = (e:any)=>{
    state.checkedList = e.target.checked ? props.colsCheckList.map((i:any)=>i.key) : []
    state.indeterminate = false
    emits('colsChecked',state.checkedList)
}

const handleCheckChange = (v:string[])=>{
    emits('colsChecked',v)
}
watch(
    () => state.checkedList,
    val => {
        state.indeterminate = !!val.length && val.length < props.colsCheckList.length;
        state.checkAll = val.length === props.colsCheckList.length;
    },
);
const calcTableHeight = () => {
    nextTick(() => {
        if (tableRef.value) {
            // 获取容器高度并减去表头等元素的高度
            const containerHeight = tableRef.value.parentElement?.clientHeight || 0
            tableHeight.value = containerHeight - 500  // 55是表头和分页器的大致高度
        }
    })
}

const handleChange = (pagination:{current:number,pageSize:number})=>{
    emits('change',pagination)
}

const handleAdd = () => {
    // 处理新增逻辑
    emits('add')
}

const onPrintTable = ()=>{
    emits('print')
}

const onExportTable = ()=>{
    // 导出当前页数据
    if(state.checkedList.length == 0) {
        showMsg("请选择导出列,操作列不会被导出",'warning')
        return
    }
    exportData(props.data)
}

const onExportTableAll = ()=>{
    
}

const exportData = (data:Array<EmptyObjectType>)=>{
    if(data.length <=0 ) {
        showMsg("没有数据可导出",'warning')
        return
    }

    exportExcel(
        data,
        props.exportFileName?props.exportFileName:`${themeConfig.value.globalTitle}_${new Date().toLocaleString()}`,
        // 选中的表头配置详细数据
        props.colsCheckList.filter((i:any)=>state.checkedList.includes(i.key)),
        "导出数据"
    )
}

onMounted(() => {
    calcTableHeight()
    window.addEventListener('resize', calcTableHeight)
})

</script>

<style lang="scss" scoped>
.common-table {
    height: 100%;
    width: 100%;
}
:deep(.ant-table-body){
    scrollbar-gutter: stable;
    &::-webkit-scrollbar {
        width: 6px;
        height: 6px;
        background: transparent;
        // opacity: 1;
        // transition: opacity 0.3s;
    }
    &:hover::-webkit-scrollbar {
        opacity: 1;
    }
    &::-webkit-scrollbar-corner,
    &::-webkit-scrollbar-thumb,
    &::-webkit-scrollbar-track {
        border-radius: 4px;
    }
    &::-webkit-scrollbar-corner,
    &::-webkit-scrollbar-track {
        background-color: transparent;
    }
    &::-webkit-scrollbar-thumb {
        background-color: transparent;
    }
    &:hover::-webkit-scrollbar-thumb {
        background-color: #a19e9e;
        &:hover {
            background-color: #ccc;
        }
    }
}

.setting-popover {
    width: 150px;
    padding: 8px;

    
    .divider {
        margin: 8px 0;
        border-top: 1px solid #f0f0f0;
    }
}
</style>